/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Views;

import Common.ConnectionDB;
import Common.Constant;
import DAO.CustomerDAO;
import Helper.CustomerHelper;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

/**
 *
 * @author KIENLT
 */
public class CustomerPopup extends javax.swing.JDialog {

    ResultSet rs = null;
    Bills bills;
    CustomerHelper cus;
    /**
     * Creates new form CustomerPopup
     */
    public CustomerPopup(Bills bills, boolean modal) {
        super(bills, modal);
        this.bills = bills;
        initComponents();
        loadTree();
        loadLanguage();
    }
    
    private void loadLanguage() {
        btnAdd.setText(Constant.getBundle().getString("add"));
    }

    private void loadTree() {
        try {
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("Customer");

            rs = CustomerDAO.FillAll(ConnectionDB.ConnectionDatabase());
            while (rs.next()) {
                DefaultMutableTreeNode node = new DefaultMutableTreeNode(new CustomerHelper(rs.getString("CID"), rs.getString("CName")));
                root.add(node);
            }
            DefaultTreeModel treeModel = new DefaultTreeModel(root);
            treeCustomer.setModel(treeModel);
            treeCustomer.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {

                @Override
                public void valueChanged(TreeSelectionEvent e) {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
                    if (node == null) {
                        return;
                    }
                    Object info = node.getUserObject();
                    if (node.isRoot()) {}
                    if (node.isLeaf()) {
                        cus = (CustomerHelper)info;
                        txtCustomer.setText(cus.getName());
//                        bills.loadCustomer(cus.getId(), cus.getName());
//                        setVisible(false);
                    }
                }
            });
        } catch (Exception ex) {
            Logger.getLogger(Bills.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void findOne() {
        try {
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("Customer");
            cus = new CustomerHelper();
            cus.setName(txtCustomer.getText());
            rs = CustomerDAO.FillOne(ConnectionDB.ConnectionDatabase(), cus);
            while (rs.next()) {
                DefaultMutableTreeNode node = new DefaultMutableTreeNode(new CustomerHelper(rs.getString("CID"), rs.getString("CName")));
                root.add(node);
            }
            DefaultTreeModel treeModel = new DefaultTreeModel(root);
            treeCustomer.setModel(treeModel);
            treeCustomer.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {

                @Override
                public void valueChanged(TreeSelectionEvent e) {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
                    if (node == null) {
                        return;
                    }
                    Object info = node.getUserObject();
                    if (node.isRoot()) {}
                    if (node.isLeaf()) {
                        cus = (CustomerHelper)info;
                        txtCustomer.setText(cus.getName());
                    }
                }
            });
        } catch (Exception ex) {
            Logger.getLogger(Bills.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        treeCustomer = new javax.swing.JTree();
        txtCustomer = new javax.swing.JTextField();
        btnAdd = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jScrollPane1.setViewportView(treeCustomer);

        txtCustomer.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtCustomerKeyReleased(evt);
            }
        });

        btnAdd.setText("jButton1");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtCustomer)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnAdd)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 345, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAdd))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        // TODO add your handling code here:
        bills.loadCustomer(cus.getId(), cus.getName());
        this.dispose();
    }//GEN-LAST:event_btnAddActionPerformed

    private void txtCustomerKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCustomerKeyReleased
        // TODO add your handling code here:
        findOne();
    }//GEN-LAST:event_txtCustomerKeyReleased

    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        /*
//         * Set the Nimbus look and feel
//         */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /*
//         * If Nimbus (introduced in Java SE 6) is not available, stay with the
//         * default look and feel. For details see
//         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(CustomerPopup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(CustomerPopup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(CustomerPopup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(CustomerPopup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /*
//         * Create and display the dialog
//         */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                CustomerPopup dialog = new CustomerPopup(new javax.swing.JFrame(), true);
//                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
//
//                    @Override
//                    public void windowClosing(java.awt.event.WindowEvent e) {
//                        System.exit(0);
//                    }
//                });
//                dialog.setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTree treeCustomer;
    private javax.swing.JTextField txtCustomer;
    // End of variables declaration//GEN-END:variables
}
